import { Init, Provide, Inject } from '@midwayjs/decorator';
import { BaseService, CoolCommException } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { GameLevelRecordEntity } from '../entity/record';
import { GameLevelInfoService } from './info';
import { CsConnService } from "../service/conn"
import { GameLevelPlayerService } from '../service/player';
import { GameRoomInfoService } from './room';
import { GameRoomInfoEntity } from '../entity/room';

/**
 * game模块-游戏记录
 */
@Provide()
export class GameLevelRecordService extends BaseService {
  @InjectEntityModel(GameLevelRecordEntity)
  gameLevelRecordEntity: Repository<GameLevelRecordEntity>;

  @InjectEntityModel(GameRoomInfoEntity)
  gameRoomInfoEntity: Repository<GameRoomInfoEntity>;

  @Inject()
  gameLevelInfoService: GameLevelInfoService;

  @Inject()
  gameLevelPlayerService: GameLevelPlayerService;

  @Inject()
  csConnService: CsConnService;




  @Inject()
  ctx;

  @Init()
  async init() {
    await super.init();
    this.setEntity(this.gameLevelRecordEntity);
  }

  /**
   * 创建房间
   * @param param
   * @returns
   */
  async add(param) {
    let { levelId, playerId, secondPlayerId, roomId } = param
    // 如果有roomid,判断房间状态
    if (roomId) {
      let roomDetail = await this.gameRoomInfoEntity.findOneBy({ id: roomId })
      if (roomDetail.status != 0) {
        throw new CoolCommException('房间已开始或已解散');
      }
    }
    // 判断解没解锁关卡  // 解锁了就把关卡信息返回回去，没解锁就抛出异常
    let { index, detail } = await this.gameLevelInfoService.isDeblocking(levelId, playerId)
    if (index != -1) {
      let record = await super.add(param)
      if (secondPlayerId) {
        let { levels } = detail
        this.csConnService.sendMessage(secondPlayerId, {
          type: "startGame",
          content: {
            roomId,
            ...detail
          }
        })
      }
      return { ...detail, record }
    } else {
      throw new CoolCommException('当前关卡未解锁');
    }
  }

  /**
   * 调整游戏记录
   * @param levelId
   * @param memberId
   * @param id
   * @param status
   * @returns
   */
  async update(param) {
    if (param.status == 1) {
      // 增加一条记录
      if (param.memberId) {
        await this.gameLevelPlayerService.add({ levelId: param.nextLevel, playerId: param.memberId })
      }
      // 正常来说只有房主可以调整游戏记录
      if (this.ctx?.user?.id) {
        await this.gameLevelPlayerService.add({ levelId: param.nextLevel, playerId: this.ctx.user.id })
      }
    }
    return await super.update(param)
  }
}
